<template>
  <div class="site-data">
    <div class="weeks">
      <span
        class="week-item"
        v-for="(week, weekIndex) in weeks"
        :key="weekIndex"
        >{{ week }}</span
      >
    </div>
    <div class="date-wrap">
      <div
        class="month-item"
        v-for="(month, monthIndex) in dates"
        :key="`_${monthIndex}`"
        id=""
      >
        <span
          class="month"
          :class="{ active: month.month == nowMonth && month.year == nowYear }"
          :style="computedMonthPosition(month.days)"
          :id="computedId(month.year, month.month)"
          >{{ month.month }}月</span
        >
        <div
          class="days"
          v-for="(dayWrap, dayWrapIndex) in month.days"
          :key="`_${dayWrapIndex}_`"
        >
          <span
            class="day"
            @click.stop="selDay(day)"
            v-for="(day, dayIndex) in dayWrap"
            :key="dayIndex"
          >
            <b
              :class="{
                active:
                  new Date(day.date).Format('yyyy/MM/dd') ==
                  new Date().Format('yyyy/MM/dd'),
              }"
              >{{ day.day }}</b
            >
          </span>
          <template v-if="dayWrap.length < 7">
            <span class="day" v-for="it in 7 - dayWrap.length" :key="`_^${it}`">
              <b></b>
            </span>
          </template>
        </div>
      </div>
    </div>
    <!--  -->
    <div class="detail" :class="{ active: showDetail }">
      <div class="back">
        <span @click.stop="hideDetail">返回</span>
        <span>最高人数:{{ topCount }}</span>
        <div class="buttons" @click.stop="openMenu">
          <button class="button button-icon">
            <span><i class="icon ion-navicon"></i></span>
          </button>
        </div>
      </div>
      <div class="weeks" @click.stop="">
        <span
          class="week-item"
          v-for="(week, weekIndex) in weeks"
          :key="weekIndex"
          >{{ week }}</span
        >
      </div>
      <div class="days-wrap-container swiper-container">
        <div class="days-wrap swiper-wrapper" v-if="detailWeeks.length">
          <div
            class="days swiper-slide"
            v-for="(it, ind) in detailWeeks"
            :key="ind"
          >
            <span
              class="day"
              @click.stop="selDay({ date: ite })"
              v-for="(ite, inde) in it"
              :key="`_*${inde}`"
            >
              <b
                :class="{
                  beforeActive:
                    new Date(ite).getDay() == new Date(nowSelDate).getDay(),
                  active:
                    new Date(ite).Format('yyyy/MM/dd') ==
                    new Date(nowSelDate).Format('yyyy/MM/dd'),
                }"
                :data-date="`${ite}`"
                >{{ new Date(ite).Format("dd") }}</b
              ></span
            >
          </div>
        </div>
      </div>
      <div class="now-sel-Date" v-if="false">
        <span
          >{{ new Date(nowSelSameTime).Format("yyyy/MM/dd") }} 周{{
            weeks[new Date(nowSelSameTime).getDay()]
          }}</span
        >
        <p class="tip">*本页面数据仅供参考</p>
        <!-- <p class="rate">昨日捕获率：{{ beforeRate }}%，销售量：{{beforeOrderCount}}，上机人次：{{beforeCount}}</p> -->
        <p class="rate"></p>
      </div>
      <div class="hours-wrap swiper-container">
        <div class="hours swiper-wrapper">
          <div
            class="hour-slide swiper-slide"
            v-for="(it, ind) in hoursItems"
            :key="ind"
          >
            <div class="hour" v-for="(hour, hourIndex) in it" :key="hourIndex">
              <div class="time">{{ hour.hour }}</div>
              <!-- <div class="time">
                {{ hour.hour }}-{{
                  Number(hour.hour) + 1 < 10
                    ? "0" + (Number(hour.hour) + 1)
                    : Number(hour.hour) + 1
                }}
              </div> -->
              <div class="val" :class="computedClass(hour)">
                <span class="tit">在线人数:</span
                ><span class="count">
                  <b>{{ hour.val }}人</b>
                  <b>销售:{{ hour.orderCount }}</b>
                  <b>总计:{{ computedClass(hour) == "gray" ? 0 : hour.rangeOrderCount }}</b>
                  <b>营业额:{{ computedClass(hour) == "gray" ? 0 : Number(hour.orderAmount).toFixed(2) }}</b>
                  <!-- <b>捕获率:{{ computedRate(hour) }}</b> -->
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!--  -->
  </div>
</template>
<script>
export default {
  name: "siteData",
  props: ["storeId"],
  data() {
    return {
      topCount:0,
      beforeRate: 0,
      beforeOrderCount: 0,
      beforeCount: 0,
      //
      weeks: ["日", "一", "二", "三", "四", "五", "六"],
      dates: [],
      detailWeeks: [],
      nowMonth: "",
      nowYear: "",
      showDetail: false,
      nowSelDate: "",
      nowSelWeekDay: "",
      detailWeeksSwiper: null,
      hoursWrapSwiper: null,
      nowSelSameTime: "",
      hours: [],
      hoursItems: [],
    };
  },
  methods: {
    computedRate(hour) {
      if (!hour.rangeOrderCount || !hour.rangeUpDownCount) {
        return "0%";
      } else {
        return (
          (hour.rangeOrderCount / hour.rangeUpDownCount).toFixed(2) * 100 + "%"
        );
      }
    },
    //
    openMenu() {
      this.hideDetail();
      document.querySelector(".sidebar-container").classList.remove("close");
    },
    //
    computedClass(hour) {
      let nowTime = new Date().getTime();
      let selTime = new Date(
        `${new Date(this.nowSelSameTime).Format("yyyy/MM/dd")} ${
          hour.hour
        }:00`
      ).getTime();
      if (selTime > nowTime) {
        return "gray";
      }
    },
    hideDetail() {
      this.showDetail = false;
      this.nowSelDate = "";
      $(".navbar").css({
        display: "block",
        opacity: "1",
      });
    },
    selDay(day) {
      if (!day.date) {
        return;
      }
      this.nowSelDate = new Date(day.date).getTime();
      let nowWeekDay = new Date(new Date(day.date).getTime()).getDay();
      this.nowSelWeekDay = nowWeekDay;
      //
      this.showDetail = true;
      $(".navbar").css({
        display: "none",
        opacity: "0",
      });
      //获取小时数据
      // this.toGetHourData(this.nowSelDate);
      this.computedDetailWeeks(this.nowSelDate);
    },
    getData(time) {
      return new Promise((resolve, reject) => {
        this.$http({
          url: "num/count",
          method: "GET",
          params: {
            storeId: this.storeId,
            begin: `${time} 00:00:00`,
            end: `${time} 23:59:59`,
          },
        })
          .then((res) => {
            res.nowTime = time;
            resolve(res);
          })
          .catch((res) => {
            reject(res);
          });
      });
    },
    async toGetHourData(nowSelDate) {
      let hours = [];
      let hoursItems = [];
      for (let i = 0; i < 24; i++) {
        hours.push({
          hour: i < 10 ? `0${i}:00` : `${i}:00`,
          val: 0,
          orderCount: 0,
          upDownCount: 0,
          rangeUpDownCount: 0,
          rangeOrderCount: 0,
          // 
          orderAmount:0,
        });
        // hours.push({
        //   hour: i < 10 ? `0${i}:30` : `${i}:30`,
        //   val: 0,
        //   orderCount: 0,
        //   upDownCount: 0,
        //   rangeUpDownCount: 0,
        //   rangeOrderCount: 0,
        // });
      }
      const oneDay = 1000 * 60 * 60 * 24;
      //
      let now = new Date(nowSelDate).Format("yyyy-MM-dd");
      let before = new Date(new Date(nowSelDate).getTime() - 1 * oneDay).Format(
        "yyyy-MM-dd"
      );
      let next = new Date(new Date(nowSelDate).getTime() + 1 * oneDay).Format(
        "yyyy-MM-dd"
      );
      let pAll = [];
      [before, now, next].forEach((item) => {
        let p = this.getData(item);
        pAll.push(p);
      });
      let res = await Promise.all(pAll);
      if (res && Array.isArray(res)) {
        res.forEach((it, ind) => {
          if (it.nowTime == now) {
            this.beforeRate = (Number(it.data.beforeRate) * 100).toFixed(1);
            this.beforeOrderCount = it.data.beforeOrderCount;
            this.beforeCount = it.data.beforeCount;
            this.topCount = it.data.topCount ? it.data.topCount : 0;
          }
          console.log("it_it", it);
          let tempHours = JSON.parse(JSON.stringify(hours));
          if (it.data.storeNumCounts && Array.isArray(it.data.storeNumCounts)) {
            it.data.storeNumCounts.forEach((ite) => {
              tempHours.forEach((item) => {
                if (item.hour == new Date(ite.addTime).Format("hh:mm")) {
                  item.val = Number(ite.bookCount) + Number(ite.onlineCount);
                }
              });
            });
          }
          // 
          if (it.data.orderAmountData && Array.isArray(it.data.orderAmountData)) {
            let tempOrderAmountArr = [];
            tempHours.forEach((item) => {
              tempOrderAmountArr.push({
                amount:0,
                time:`${new Date(it.nowTime).Format("yyyy-MM-dd")} ${item.hour}`,
              })
            })
            it.data.orderAmountData.forEach(ite=>{
              tempOrderAmountArr.forEach((item) => {
                if (new Date(item.time).Format("hh:mm") == new Date(ite.time).Format("hh:mm")) {
                  item.amount = Number(ite.amount);
                }
              });
            })
            it.data.orderAmountData = tempOrderAmountArr;
          }
          console.log("it.data.orderAmountData",it.data.orderAmountData)
          if (it.data.orderAmountData && Array.isArray(it.data.orderAmountData)) {
            let tempOrderAmount = 0;
            it.data.orderAmountData.forEach((ite) => {
              tempOrderAmount += Number(ite.amount);
              tempHours.forEach((item) => {
                if (item.hour == new Date(ite.time).Format("hh:mm")) {
                  // item.orderAmount = Number(ite.amount);
                  item.orderAmount = Number(tempOrderAmount);
                }
              });
            });
          }
          //
          if (it.data.orderData && Array.isArray(it.data.orderData)) {
            it.data.orderData.forEach((ite) => {
              ite.time = ite.time.replace(/\-/g, "/");
              console.log("orderData.time", ite.time);
              tempHours.forEach((item) => {
                if (item.hour == new Date(ite.time).Format("hh:mm")) {
                  item.orderCount = Number(ite.count);
                  item.rangeOrderCount = Number(ite.count);
                }
              });
            });
          }
          //
          if (it.data.upData && Array.isArray(it.data.upData)) {
            it.data.upData.forEach((ite) => {
              ite.time = ite.time.replace(/\-/g, "/");
              console.log("upData.time", ite.time);
              tempHours.forEach((item) => {
                if (item.hour == new Date(ite.time).Format("hh:mm")) {
                  item.upDownCount = Number(ite.count);
                  item.rangeUpDownCount = Number(ite.count);
                }
              });
            });
          }
          //
          tempHours.forEach((it, ind) => {
            for (let i = 0; i < ind; i++) {
              it.rangeUpDownCount += Number(tempHours[i].upDownCount);
              it.rangeOrderCount += Number(tempHours[i].orderCount);
            }
          });
          console.log("tempHours", tempHours);
          //
          it.formatData = tempHours;
        });
      }
      console.log(res);
      //
      if (res && Array.isArray(res) && res.length) {
        res.forEach((it) => {
          hoursItems.push(it.formatData);
        });
      }
      this.hoursItems = hoursItems;
      //
      setTimeout(() => {
        this.$nextTick(() => {
          if (this.hoursWrapSwiper) {
            this.hoursWrapSwiper.destroy();
            this.hoursWrapSwiper = null;
          }
          this.hoursWrapSwiper = new Swiper(".hours-wrap", {
            initialSlide: 1,
            onSlideChangeStart: (swiper) => {
              if (swiper.activeIndex == 0) {
                let nowSelDay = new Date(
                  new Date(nowSelDate).getTime() - 1 * oneDay
                ).Format("yyyy/MM/dd");
                this.selDay({ date: nowSelDay });
              } else if (swiper.activeIndex == 2) {
                let nowSelDay = new Date(
                  new Date(nowSelDate).getTime() + 1 * oneDay
                ).Format("yyyy/MM/dd");
                this.selDay({ date: nowSelDay });
              }
            },
          });
        });
      }, 100);
    },
    computedDetailWeeks(nowSelDate) {
      //
      let thisWeek = [];
      const beforeDays = [];
      const lastDays = [];
      const oneDay = 1000 * 60 * 60 * 24;
      for (let i = this.nowSelWeekDay; i > 0; i--) {
        beforeDays.push(
          new Date(new Date(nowSelDate).getTime() - i * oneDay).Format(
            "yyyy/MM/dd"
          )
        );
      }
      let index = -1;
      for (let i = this.nowSelWeekDay; i < 7; i++) {
        index++;
        lastDays.push(
          new Date(new Date(nowSelDate).getTime() + index * oneDay).Format(
            "yyyy/MM/dd"
          )
        );
      }
      thisWeek = [...beforeDays, ...lastDays];
      console.log(thisWeek);
      //
      let firstDay = thisWeek[0];
      let lastDay = thisWeek[thisWeek.length - 1];
      let lastWeek = [];
      let nextWeek = [];
      for (let i = 7; i > 0; i--) {
        lastWeek.push(
          new Date(new Date(firstDay).getTime() - i * oneDay).Format(
            "yyyy/MM/dd"
          )
        );
      }
      console.log("lastWeek", lastWeek);
      for (let i = 1; i < 8; i++) {
        nextWeek.push(
          new Date(new Date(lastDay).getTime() + i * oneDay).Format(
            "yyyy/MM/dd"
          )
        );
      }
      console.log("nextWeek", nextWeek);
      //
      this.detailWeeks = [];
      this.detailWeeks = [lastWeek, thisWeek, nextWeek];
      if (this.detailWeeksSwiper) {
        this.detailWeeksSwiper.activeIndex = 1;
      }
      setTimeout(() => {
        this.$nextTick(() => {
          if (this.detailWeeksSwiper) {
            this.detailWeeksSwiper.destroy();
            this.detailWeeksSwiper = null;
          }
          this.detailWeeksSwiper = new Swiper(".days-wrap-container", {
            initialSlide: 1,
            speed: 500,
            onSlideChangeStart: (swiper) => {
              if (swiper.activeIndex == 0) {
                console.log("prev", nowSelDate);
                nowSelDate = new Date(
                  new Date(nowSelDate).getTime() - 7 * oneDay
                ).Format("yyyy/MM/dd");
                console.log(nowSelDate);
                this.computedDetailWeeks(nowSelDate);
              } else if (swiper.activeIndex == 2) {
                console.log("next", nowSelDate);
                nowSelDate = new Date(
                  new Date(nowSelDate).getTime() + 7 * oneDay
                ).Format("yyyy/MM/dd");
                this.computedDetailWeeks(nowSelDate);
              }
            },
            onSlideChangeEnd: () => {
              this.nowSelSameTime = $(
                ".swiper-slide-active b.beforeActive"
              )[0].getAttribute("data-date");
              this.toGetHourData(this.nowSelSameTime);
            },
          });
        });
      }, 100);
    },
    computedMonthPosition(days) {
      let i = 0;
      days[0].forEach((it) => {
        if (!it.date) {
          i++;
        }
      });
      let paddingLeft = i * 14.5;
      return `padding-left:${paddingLeft}%;`;
    },
    computedId(year, month) {
      if (month < 10) {
        return `${year}/0${month}`;
      }
      return `${year}/${month}`;
    },
    scrollToView() {
      this.selDay({ date: new Date().Format("yyyy/MM/dd") });
      setTimeout(() => {
        let idStr = `${new Date().Format("yyyy/MM")}`;
        console.log("idStr", idStr);
        this.$nextTick(() => {
          document.getElementById(idStr).scrollIntoView();
        });
      }, 500);
    },
  },
  mounted() {
    const date = new Date();
    const year = date.getFullYear();
    this.nowYear = year;
    const month = date.getMonth();
    this.nowMonth = month + 1;
    const startYear = 2022;
    let dates = [];
    function getDates(y) {
      for (let m = 1; m <= 12; m++) {
        let date = [];
        const nowWeek = new Date(`${y}/${m}/1`).getDay();
        const days = new Date(y, m, 0).getDate();
        for (let i = 0; i < nowWeek; i++) {
          date.push({
            date: "",
            day: "",
            hasData: false,
          });
        }
        for (let j = 1; j <= days; j++) {
          date.push({
            date: `${y}/${m}/${j < 10 ? "0" + j : j}`,
            day: j,
            hasData: false,
          });
        }
        let newDate = [];
        for (let i = 0; i < Math.ceil(date.length / 7); i++) {
          newDate.push(date.slice(i * 7, (i + 1) * 7));
        }
        dates.push({
          year: y,
          month: m,
          days: newDate,
        });
      }
    }
    for (let i = year - startYear; i >= 0; i--) {
      getDates(year - i);
    }
    console.log("dates", dates);
    let showDataMonth = 2 * 12;
    if (dates.length > showDataMonth) {
      dates = dates.slice(dates.length - showDataMonth, dates.length);
    }
    console.log("dates", dates);
    this.dates = dates;
    this.scrollToView();
  },
};
</script>
<style lang="scss" scoped>
.site-data {
  width: 100%;
  height: 100%;
  overflow: hidden;
  position: relative;
  .weeks {
    width: 100%;
    height: 0.59rem;
    display: flex;
    background-color: #fff;
    box-shadow: 0 0 0.3rem rgba(0, 0, 0, 0.159);
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    z-index: 9;
    .week-item {
      flex: 1;
      box-sizing: border-box;
      font-size: 0.25rem;
      font-weight: 500;
      display: flex;
      justify-content: center;
      align-items: center;
    }
  }
  .date-wrap {
    width: 100%;
    padding-top: 44px;
    height: 100%;
    background-color: #fff;
    overflow: hidden;
    overflow-y: auto;
    .month-item {
      width: 100%;
      padding: 0.25rem 0;
      .month {
        font-size: 0.4rem;
        font-weight: bold;
        &.active {
          color: rgb(251, 70, 55);
        }
      }
    }
  }
  .days {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    transition: all 0.3s;
    .day {
      display: inline-block;
      width: 14.3%;
      padding: 0.25rem 0;
      box-sizing: border-box;
      border-top: 1px solid #eee;
      font-size: 0.28rem;
      font-weight: bold;
      color: #333;
      display: flex;
      justify-content: center;
      align-items: center;
      b {
        display: inline-block;
        width: 0.5rem;
        height: 0.5rem;
        border-radius: 0.25rem;
        text-align: center;
        line-height: 0.5rem;
        &.active {
          background-color: rgb(251, 70, 55) !important;
          color: #fff;
        }
      }
      &:first-child,
      &:last-child {
        color: #999;
      }
    }
  }
  .detail {
    position: fixed;
    right: 0;
    left: 0;
    bottom: 0;
    z-index: 99999;
    width: 100%;
    height: 100%;
    background-color: #fff;
    border-top: 1px solid #eee;
    transition: all 0.3s;
    transform: translateY(100%);
    &.active {
      transform: translateY(0);
    }
    .weeks {
      position: relative;
      top: 0;
    }
    .back {
      width: 100%;
      height: 45px;
      background-color: #fff;
      font-size: 0.28rem;
      line-height: 45px;
      padding-left: 0.2rem;
      color: rgb(251, 70, 55);
      z-index: 999;
      display: flex;
      justify-content: space-between;
      padding-right: 0.2rem;
    }
    .days-wrap-container {
      height: 0.9rem;
      .days {
        height: 0.9rem;
        display: flex;
        align-items: center;
        .day {
          b {
            &.beforeActive {
              background-color: #333;
              color: #fff;
            }
          }
        }
      }
    }

    .now-sel-Date {
      display: flex;
      justify-content: center;
      height: 1.5rem;
      font-size: 0.3rem;
      font-weight: bold;
      color: #666;
      border-bottom: 1px solid #eee;
      flex-wrap: wrap;
      .tip,
      .rate {
        text-align: center;
        width: 100%;
        color: #999;
        font-size: 0.24rem;
        height: 0.5rem;
        line-height: 0.5rem;
        margin: 0;
      }
      .rate {
        color: #fa6b5e;
        font-weight: bold;
      }
    }
    .hours-wrap {
      /* height: calc(100% - 45px - 0.59rem - 0.9rem - 1.6rem); */
      height: calc(100% - 45px - 0.59rem - 0.9rem - 0rem);
      overflow: hidden;
      overflow-y: auto;
    }
    .hours {
      width: 100%;
      padding: 0.24rem;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .hour {
        position: relative;
        height: 0.7rem;
        display: flex;
        align-items: center;
        .time {
          font-size: 0.24rem;
          color: #666;
          width: 0.7rem;
          white-space: nowrap;
        }
        .val {
          width: calc(100% - 1.259rem);
          height: 0.5rem;
          /* background-color: rgb(231, 231, 231); */
          /* border-radius: 0.2rem; */
          display: flex;
          align-items: center;
          border-bottom: 1px solid rgb(231, 231, 231);
          display: flex;
          span {
            /* color: #f4f4f4; */
            font-size: 0.2rem;
            padding-left: 0.159rem;
            /* text-shadow: 0 0 0.05rem rgb(201, 32, 17); */
            color: #fa6b5e;
            white-space: nowrap;
          }
          .count {
            flex: 1;
            box-sizing: border-box;
            display: flex;
            justify-content: space-around;
            padding-left: 9%;
            b {
              flex: 1.5;
              text-align: left;
              font-weight: normal;
              &:first-child {
                flex: 1;
              }
            }
          }
          &.gray {
            span {
              color: #999;
            }
          }
        }
      }
    }
  }
}
</style>
